<template>
  <view class="history-container">
    <view class="header">
      <text class="title">积分历史</text>
    </view>
    
    <view class="history-list">
      <view 
        v-for="record in history" 
        :key="record.id" 
        class="history-item"
      >
        <view class="record-info">
          <text class="description">{{ record.description }}</text>
          <text class="date">{{ formatDate(record.created_at) }}</text>
        </view>
        <view class="points" :class="{ 'positive': record.points > 0, 'negative': record.points < 0 }">
          {{ record.points > 0 ? '+' : '' }}{{ record.points }}
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { getPointsHistory } from '@/api/points.js'
import { formatTime } from '@/utils/date-utils.js'
import { handleApiError } from '@/utils/error-handler.js'
import { validateBeforeOperation } from '@/utils/auth'

// 积分历史数据
const history = ref([])

// 格式化日期
const formatDate = (date) => {
  return formatTime(new Date(date))
}

// 获取积分历史
const fetchHistory = async () => {
  try {
    // 使用统一的登录验证
    const isLoggedIn = validateBeforeOperation('查看积分历史')
    if (!isLoggedIn) {
      return
    }
    const response = await getPointsHistory()
    history.value = response.data
  } catch (error) {
    handleApiError(error, '获取积分历史')
  }
}

// 页面加载时获取历史记录
onMounted(() => {
  fetchHistory()
})
</script>

<style scoped>
.history-container {
  padding: 20rpx;
}

.header {
  text-align: center;
  margin-bottom: 30rpx;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.history-list {
  background: #fff;
  border-radius: 10rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.history-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx 20rpx;
  border-bottom: 1rpx solid #eee;
}

.history-item:last-child {
  border-bottom: none;
}

.record-info {
  flex: 1;
}

.description {
  font-size: 30rpx;
  color: #333;
  display: block;
  margin-bottom: 10rpx;
}

.date {
  font-size: 24rpx;
  color: #999;
}

.points {
  font-size: 32rpx;
  font-weight: bold;
}

.points.positive {
  color: #4caf50;
}

.points.negative {
  color: #f44336;
}
</style>